package play.go.controller;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import play.go.GoServer;
import play.go.meta.LobbyMeta;
import play.go.meta.PlayerMeta;
import play.go.model.Lobby;
import play.go.model.Player;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

/**
 * Entry to a new game.
 * <p>
 * rank = 1 only
 * </p>
 * 
 * @author shuji.w6e
 * @since 0.1.0
 */
public class EntryController extends AbstructGoController {

    @Override
    public Navigation run() throws Exception {
        // TODO こっちは入退出の管理のみ
        Player player = getPlayer();
        Transaction tx = Datastore.beginTransaction();
        Key rank = Datastore.createKey(LobbyMeta.get(), 1);
        Lobby lobby = Datastore.query(tx, LobbyMeta.get(), rank).asSingle();
        if (lobby != null) {// matched!
            if (lobby.getPlayer().equals(player.getKey()))
                throw new IllegalStateException("invalid request.");
            Datastore.delete(tx, lobby.getKey());
        } else {
            Lobby newLobby = new Lobby();
            newLobby.setKey(Datastore.allocateId(rank, LobbyMeta.get()));
            newLobby.setPlayer(player.getKey());
            Datastore.put(tx, newLobby);
        }
        Datastore.commit(tx);
        if (lobby != null) {
            GoServer.start(
                player,
                Datastore.get(PlayerMeta.get(), lobby.getPlayer()));
        }
        return text("" + player.getKey().getId());
    }
}
